(function () {
    var contractId=jQuery('#contractId').val();
    var contractType=jQuery('#contractType').val();
    var paySum=jQuery('#paySum').val();
    var dates=new Array();
    var firstdate=null;
    var nextdate=null;
    var num=0;
//获取显示页面数据 服务器分页
    var serverData = {};
    var	serverTable;
    jQuery(document).ready(function (){
        serverTable = jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url": window.rootPath + '/ui/paySchedule/'+contractId+'/'+contractType+'/getData',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                    data: null
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {
                        var id=data.contractId;
                        var operate ='<input type="checkbox" class="checkchild">';
                        return operate;
                    }
                },
                {
                    data: 'sAccountsReceivableTypeId.sAccountsReceivableTypeName'
                },
                {
                    data: 'nTotalPrice'
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {
                        var amount= parseFloat(data.nTotalPrice);
                       // var contractSum= parseFloat(paySum);
                        var result=amount/paySum;
                        //var operate=paySum <= 0 ? "0%" : (Math.round(amount / paySum * 10000) / 100.00 + "%");
                        var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';
                        return operate;
                    }
                },
                {
                    data:'dAccountsReceivablePlanDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data:'sMemo',
	                render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 40) ? '<font title="'+data+'">'+data.substring(0,40)+'...'+'</font>' : data;
						}
					}
                }
            ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
        //var url = window.rootPath + '/ui/paySchedule/'+contractId+'/'+contractType+'/getPlan';
        //jQuery.ajax({
        //    type: 'get',
        //    url: encodeURI(url),
        //    dataType: 'json',
        //    contentType: 'application/json;charset=utf-8',
        //    success: function (data){
        //        for(var i=0;i<7;i++){
        //            dates[i]=moment(data.data[i].payDate).format('YYYY-MM-DD');
        //        };
        //    }
        //});
    });
    var palnAmount;
    var oldDate;
    var amountOld;
    //编辑计划
    jQuery('.editBtn').on('click', function () {
        var selects=getSelect("#dataTable",1);
        if(selects.length>1){
            $.springLemonDialog({
                content: '只能编辑一条记录',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }
        else if(selects.length==0){
            $.springLemonDialog({
                content: '请选择要编辑的记录',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length==1){
            jQuery('#id').val(selects[0].id);
            jQuery('#accountsReceivableType').val(selects[0].sAccountsReceivableTypeId.id);
            jQuery('#amount').val(selects[0].nTotalPrice);
            palnAmount=jQuery('#amount').val();
            amountOld= parseFloat(palnAmount);
            var result=amountOld/paySum;
            var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';
            jQuery('#ratio').val(operate);
            if(selects[0].dAccountsReceivablePlanDate){
            var time=moment(selects[0].dAccountsReceivablePlanDate).format('YYYY-MM-DD');
            jQuery('#payDate').val(time);
            }
            else{
                jQuery('#payDate').val("");
            }
            oldDate=jQuery('#payDate').val();
            jQuery('#memo').val(selects[0].sMemo);
            jQuery('#paymentEditModal').modal('show');
            jQuery('#createTime').val(selects[0].createTime);
        }
    });
    
    jQuery('.addBtn').on('click', function () {
    	jQuery('#id').val("");
        jQuery('#accountsReceivableType').val("");
        jQuery('#amount').val("");
        palnAmount=jQuery('#amount').val();
        amountOld= parseFloat(palnAmount);
        var result=amountOld/paySum;
        //var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';
        //jQuery('#ratio').val(operate);
        jQuery('#ratio').val("0%");
        jQuery('#payDate').val("");
        oldDate=jQuery('#payDate').val();
        jQuery('#memo').val("");
        jQuery('#paymentEditModal').modal('show');
        jQuery('#createTime').val(new Date());
    });
    
    jQuery('.delBtn').on('click', function () {
        var selects=getSelect("#dataTable",1);
        if(selects.length < 1){
            $.springLemonDialog({
                content: '请选择需要删除的数据',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                }
            });
        }else if(selects.length>0){
        	var ids=selects[0].id;
        	for(var i=1;i<selects.length;i++){
        		ids += ',' + selects[i].id;  
		    }
        	var url = window.rootPath+"/ui/paySchedule/delbyid/"+contractId+"/"+contractType + "/" + ids;
        	jQuery.ajax({
               	type : 'get',
               	url : encodeURI(url),
               	dataType : 'json',
               	contentType : 'application/json;charset=utf-8',
               	success : function(data) {
               		alert("删除成功！");
               		serverTable.draw(true);
               	}
        	});
        }
    });
    //比例转换
    jQuery('#ratio').blur(function(){
        var ratio=jQuery('#ratio').val();
        var operate=parseFloat(ratio)/100 * paySum;
        jQuery('#amount').val(operate.toFixed(2));
    });
    //金额转换
    jQuery('#amount').blur(function(){
        var palnAmount=jQuery('#amount').val();
        var amount= parseFloat(palnAmount);
        var result=amount/paySum;
        var operate=paySum <= 0 ? "0%" : (Math.round(result * 10000)/100).toFixed(2) + '%';
        jQuery('#ratio').val(operate);
    });
    ///编辑保存
    jQuery('.saveBtn').on('click', function () {
        if (jQuery("#paymentEditForm") && !jQuery("#paymentEditForm").Validform({
                tiptype : 3,
                showAllError : true
            }).check(false)) {
            return;
        };
        var id = jQuery('#id').val();
        //var fund = $('#accountsReceivableType').val();
        var amount = jQuery('#amount').val();
        var payDate=jQuery('#payDate').val();//当前款项回款时间
        var memo = jQuery('#memo').val();
        var contractId=jQuery('#contractId').val();
        var contractType=jQuery('#contractType').val();
        var createTime=jQuery('#createTime').val;
        var sAccountsReceivableTypeId=$('#accountsReceivableType').val();
        var accountsReceivableType = {
        		"id": sAccountsReceivableTypeId
        };
        var mid=amount-amountOld;
        if(parseFloat(amount)==0.0){
        	payDate = null;
        }
        //firstdate=moment(payDate).format('YYYY-MM-DD');
        jQuery(".saveBtn").attr("disabled", true);
        
        var url=window.rootPath+'/ui/payment/isInitial/'+contractId+'/'+contractType;
        jQuery.ajax({
            type: 'get',
            url: encodeURI(url),
            dataType: 'json',
            contentType: 'application/json;charset=utf-8',
            success: function (data) {
                var a=data.scheduleSum+mid;
                var b=data.paidSum;//回款总额
                var c=data.paymentSum;//开票总额
                if(data.code==0) {
                	
                	var url = window.rootPath + '/ui/paySchedule/updata';
                    var d = {
                        "id": id,
                        "sAccountsReceivableTypeId": accountsReceivableType,
                        "nTotalPrice": amount,
                        "dAccountsReceivablePlanDate": payDate,
                        "sContractId": contractId,
                        "sContractType": contractType,
                        "sMemo": memo,
                        "createTime": createTime
                    };
                    jQuery.ajax({
                        type: 'post',
                        url: encodeURI(url),
                        data: JSON.stringify(d),
                        dataType: 'json',
                        contentType: 'application/json;charset=utf-8',
                        success: function (data) {
                        	alert("保存成功！");
                        	jQuery('#paymentEditModal').modal('hide');
                            serverTable.draw(true);
                            jQuery(".saveBtn").attr("disabled", false);
                        }
                    });
                	
                	
                    //判断是否为新增数据
                    /*if (id == '') {
                        var url = window.rootPath + "/api/paymentInitials";
                        var d = {
                            "fund": fund,
                            "amount": amount,
                            "payDate": payDate,
                            "memo": memo,
                            "contractId": contractId,
                            "contractType": contractType
                        };
                        jQuery.ajax({
                            type: 'post',
                            url: encodeURI(url),
                            data: JSON.stringify(d),
                            dataType: 'json',
                            contentType: 'application/json;charset=utf-8',
                            success: function (data) {
                                jQuery('#paymentEditModal').modal('hide');
                                serverTable.draw(true);
                                jQuery(".saveBtn").attr("disabled", false);
                            }
                        });
                    } else {//是否为编辑数据
                        var url = window.rootPath + '/api/paymentInitials/' + id;
                        var d = {
                            "id": id,
                            "createTime": createTime,
                            "fund": fund,
                            "amount": amount,
                            "payDate": payDate,
                            "memo": memo,
                            "contractId": contractId,
                            "contractType": contractType
                        };
                        jQuery.ajax({
                            type: 'patch',
                            url: encodeURI(url),
                            data: JSON.stringify(d),
                            dataType: 'json',
                            contentType: 'application/json;charset=utf-8',
                            success: function (data) {
                                jQuery('#paymentEditModal').modal('hide');
                                serverTable.draw(true);
                                if (palnAmount != amount || oldDate != payDate) {
                                    var url = window.rootPath + '/ui/paySchedule/updata';
                                    var d = {
                                        "id": id,
                                        "fund": fund,
                                        "scheduleSum": amount,
                                        "schedulePayDate": payDate,
                                        "contractId": contractId,
                                        "contractType": contractType
                                    };
                                    jQuery.ajax({
                                        type: 'post',
                                        url: encodeURI(url),
                                        data: JSON.stringify(d),
                                        dataType: 'json',
                                        contentType: 'application/json;charset=utf-8',
                                        success: function (data) {
                                        }
                                    });
                                }
                                jQuery(".saveBtn").attr("disabled", false);
                            }
                        });
                    }*/
                }
                else{
                    if(b<c){
                        if(a<b){ab();}
                        else if(a<c){ac();}
                        else{save()}
                    }
                        else{
                        if(a<c){ac()}
                        else if(a<b){ab()}
                        else{save()}
                        }
                    }
                }
        });
        function ab() {
            $.springLemonDialog({
                content: '编辑的金额使计划总额小于回款总额，修改为合适的计划金额！',// 确认文本
                clickButton: function (sender, modal, index) {// 按钮事件处理
                    $(this).closeDialog(modal);
                    jQuery(".saveBtn").attr("disabled", false);
                }
            });
        }
            function ac(){
                $.springLemonDialog({
                    content: '编辑的金额使计划总额小于开票总额，修改为合适的计划金额！',// 确认文本
                    clickButton: function (sender, modal, index) {// 按钮事件处理
                        $(this).closeDialog(modal);
                        jQuery(".saveBtn").attr("disabled", false);
                    }
                });
            };
            function save(){
            	
            	var url = window.rootPath + '/ui/paySchedule/updata';
                var d = {
            		"id": id,
                    "sAccountsReceivableTypeId": accountsReceivableType,
                    "nTotalPrice": amount,
                    "dAccountsReceivablePlanDate": payDate,
                    "sContractId": contractId,
                    "sContractType": contractType,
                    "sMemo": memo,
                    "createTime": createTime
                };
                jQuery.ajax({
                    type: 'post',
                    url: encodeURI(url),
                    data: JSON.stringify(d),
                    dataType: 'json',
                    contentType: 'application/json;charset=utf-8',
                    success: function (data) {
                    	alert("保存成功！");
                    	jQuery('#paymentEditModal').modal('hide');
                        serverTable.draw(true);
                        jQuery(".saveBtn").attr("disabled", false);
                    }
                });
                
            //判断是否为新增数据
                /*if (id == '') {
                    var url = window.rootPath + "/api/paymentInitials";
                    var d = {
                        "fund": fund,
                        "amount": amount,
                        "payDate": payDate,
                        "memo": memo,
                        "contractId": contractId,
                        "contractType": contractType
                    };
                    jQuery.ajax({
                        type: 'post',
                        url: encodeURI(url),
                        data: JSON.stringify(d),
                        dataType: 'json',
                        contentType: 'application/json;charset=utf-8',
                        success: function (data) {
                            jQuery('#paymentEditModal').modal('hide');
                            serverTable.draw(true);
                            jQuery(".saveBtn").attr("disabled", false);
                        }
                    });
                } else {//是否为编辑数据
                    var url = window.rootPath + '/api/paymentInitials/' + id;
                    var d = {
                        "id": id,
                        "createTime": createTime,
                        "fund": fund,
                        "amount": amount,
                        "payDate": payDate,
                        "memo": memo,
                        "contractId": contractId,
                        "contractType": contractType
                    };
                    jQuery.ajax({
                        type: 'patch',
                        url: encodeURI(url),
                        data: JSON.stringify(d),
                        dataType: 'json',
                        contentType: 'application/json;charset=utf-8',
                        success: function (data) {
                            jQuery('#paymentEditModal').modal('hide');
                            serverTable.draw(true);
                            if(palnAmount!=amount||oldDate!=payDate){
                                var url = window.rootPath + '/ui/paySchedule/updata';
                                var d = {
                                    "id": id,
                                    "fund": fund,
                                    "scheduleSum": amount,
                                    "schedulePayDate": payDate,
                                    "contractId": contractId,
                                    "contractType":contractType
                                };
                                jQuery.ajax({
                                    type: 'post',
                                    url: encodeURI(url),
                                    data: JSON.stringify(d),
                                    dataType: 'json',
                                    contentType: 'application/json;charset=utf-8',
                                    success: function (data) {
                                    }
                                });
                            }
                            jQuery(".saveBtn").attr("disabled", false);
                        }
                    });
                }*/
            }
        //if(num==0){
        //    jQuery(".saveBtn").attr("disabled", true);
        //    //判断是否为新增数据
        //    if (id == '') {
        //        var url = window.rootPath + "/api/paymentInitials";
        //        var d = {
        //            "fund": fund,
        //            "amount": amount,
        //            "payDate": payDate,
        //            "memo": memo,
        //            "contractId": contractId,
        //            "contractType": contractType
        //        };
        //        jQuery.ajax({
        //            type: 'post',
        //            url: encodeURI(url),
        //            data: JSON.stringify(d),
        //            dataType: 'json',
        //            contentType: 'application/json;charset=utf-8',
        //            success: function (data) {
        //                jQuery('#paymentEditModal').modal('hide');
        //                serverTable.draw(true);
        //                jQuery(".saveBtn").attr("disabled", false);
        //                var url = window.rootPath + '/ui/paySchedule/updata';
        //                var d = {
        //                    "id": id,
        //                    "fund": fund,
        //                    "scheduleSum": amount,
        //                    "schedulePayDate": payDate,
        //                    "contractId": contractId
        //                };
        //                jQuery.ajax({
        //                    type: 'post',
        //                    url: encodeURI(url),
        //                    data: JSON.stringify(d),
        //                    dataType: 'json',
        //                    contentType: 'application/json;charset=utf-8',
        //                    success: function (data) {
        //                    }
        //                });
        //                var url = window.rootPath + '/ui/paySchedule/'+contractId+'/'+contractType+'/getPlan';
        //                jQuery.ajax({
        //                    type: 'get',
        //                    url: encodeURI(url),
        //                    dataType: 'json',
        //                    contentType: 'application/json;charset=utf-8',
        //                    success: function (data){
        //                        for(var i=0;i<7;i++){
        //                            dates[i]=moment(data.data[i].payDate).format('YYYY-MM-DD');
        //                        };
        //                    }
        //                });
        //            }
        //        });
        //    } else {//是否为编辑数据
        //        var url = window.rootPath + '/api/paymentInitials/' + id;
        //        var d = {
        //            "id": id,
        //            "createTime": createTime,
        //            "fund": fund,
        //            "amount": amount,
        //            "payDate": payDate,
        //            "memo": memo,
        //            "contractId": contractId,
        //            "contractType": contractType
        //        };
        //        jQuery.ajax({
        //            type: 'patch',
        //            url: encodeURI(url),
        //            data: JSON.stringify(d),
        //            dataType: 'json',
        //            contentType: 'application/json;charset=utf-8',
        //            success: function (data) {
        //                jQuery('#paymentEditModal').modal('hide');
        //                serverTable.draw(true);
        //                jQuery(".saveBtn").attr("disabled", false);
        //                var url = window.rootPath + '/ui/paySchedule/updata';
        //                var d = {
        //                    "id": id,
        //                    "fund": fund,
        //                    "scheduleSum": amount,
        //                    "schedulePayDate": payDate,
        //                    "contractId": contractId
        //                };
        //                jQuery.ajax({
        //                    type: 'post',
        //                    url: encodeURI(url),
        //                    data: JSON.stringify(d),
        //                    dataType: 'json',
        //                    contentType: 'application/json;charset=utf-8',
        //                    success: function (data) {
        //                    }
        //                });
        //                var url = window.rootPath + '/ui/paySchedule/'+contractId+'/'+contractType+'/getPlan';
        //                jQuery.ajax({
        //                    type: 'get',
        //                    url: encodeURI(url),
        //                    dataType: 'json',
        //                    contentType: 'application/json;charset=utf-8',
        //                    success: function (data){
        //                        for(var i=0;i<7;i++){
        //                            dates[i]=moment(data.data[i].payDate).format('YYYY-MM-DD');
        //                        };
        //                    }
        //                });
        //            }
        //        });
        //    }
        //}
        //else {
        //    //var payDate=new Date(paydate.replace(/\-/g, "\/"));
        //    for(var i=0;i<=num-1;i++){
        //        //var dates=new Date(dates.replace(/\-/g, "\/"));
        //        nextdate=moment(dates[i]).format('YYYY-MM-DD');
        //        if(nextdate<=firstdate){
        //            var code=1;
        //            continue
        //        }
        //        else{
        //           var code=0;
        //            break}
        //    }
        //    if(code==1){
        //        for(var j=num+1;j<7;j++){
        //            //var nextdate=new Date(dates[j].replace(/\-/g, "\/"));
        //            nextdate=moment(dates[j]).format('YYYY-MM-DD');
        //            if(nextdate>=firstdate){
        //                var code=1;
        //                continue
        //            }
        //            else{
        //                var code=0;
        //                break}
        //        }
        //        if(code==1){
        //            jQuery(".saveBtn").attr("disabled", true);
        //            //判断是否为新增数据
        //            if (id == '') {
        //                var url = window.rootPath + "/api/paymentInitials";
        //                var d = {
        //                    "fund": fund,
        //                    "amount": amount,
        //                    "payDate": payDate,
        //                    "memo": memo,
        //                    "contractId": contractId,
        //                    "contractType": contractType
        //                };
        //                jQuery.ajax({
        //                    type: 'post',
        //                    url: encodeURI(url),
        //                    data: JSON.stringify(d),
        //                    dataType: 'json',
        //                    contentType: 'application/json;charset=utf-8',
        //                    success: function (data) {
        //                        jQuery('#paymentEditModal').modal('hide');
        //                        serverTable.draw(true);
        //                        jQuery('#excessiveDate').val(data.payDate);
        //                        jQuery(".saveBtn").attr("disabled", false);
        //                        var url = window.rootPath + '/ui/paySchedule/updata';
        //                        var d = {
        //                            "id": id,
        //                            "fund": fund,
        //                            "scheduleSum": amount,
        //                            "schedulePayDate": payDate,
        //                            "contractId": contractId
        //                        };
        //                        jQuery.ajax({
        //                            type: 'post',
        //                            url: encodeURI(url),
        //                            data: JSON.stringify(d),
        //                            dataType: 'json',
        //                            contentType: 'application/json;charset=utf-8',
        //                            success: function (data) {
        //                            }
        //                        });
        //                        var url = window.rootPath + '/ui/paySchedule/'+contractId+'/'+contractType+'/getPlan';
        //                        jQuery.ajax({
        //                            type: 'get',
        //                            url: encodeURI(url),
        //                            dataType: 'json',
        //                            contentType: 'application/json;charset=utf-8',
        //                            success: function (data){
        //                                for(var i=0;i<7;i++){
        //                                    dates[i]=moment(data.data[i].payDate).format('YYYY-MM-DD');
        //                                };
        //                            }
        //                        });
        //                    }
        //                });
        //            } else {//是否为编辑数据
        //                var url = window.rootPath + '/api/paymentInitials/' + id;
        //                var d = {
        //                    "id": id,
        //                    "createTime": createTime,
        //                    "fund": fund,
        //                    "amount": amount,
        //                    "payDate": payDate,
        //                    "memo": memo,
        //                    "contractId": contractId,
        //                    "contractType": contractType
        //                };
        //                jQuery.ajax({
        //                    type: 'patch',
        //                    url: encodeURI(url),
        //                    data: JSON.stringify(d),
        //                    dataType: 'json',
        //                    contentType: 'application/json;charset=utf-8',
        //                    success: function (data) {
        //                        jQuery('#paymentEditModal').modal('hide');
        //                        serverTable.draw(true);
        //                        jQuery('#excessiveDate').val(data.payDate);
        //                        jQuery(".saveBtn").attr("disabled", false);
        //                        var url = window.rootPath + '/ui/paySchedule/updata';
        //                        var d = {
        //                            "id": id,
        //                            "fund": fund,
        //                            "scheduleSum": amount,
        //                            "schedulePayDate": payDate,
        //                            "contractId": contractId
        //                        };
        //                        jQuery.ajax({
        //                            type: 'post',
        //                            url: encodeURI(url),
        //                            data: JSON.stringify(d),
        //                            dataType: 'json',
        //                            contentType: 'application/json;charset=utf-8',
        //                            success: function (data) {
        //                            }
        //                        });
        //                        var url = window.rootPath + '/ui/paySchedule/'+contractId+'/'+contractType+'/getPlan';
        //                        jQuery.ajax({
        //                            type: 'get',
        //                            url: encodeURI(url),
        //                            dataType: 'json',
        //                            contentType: 'application/json;charset=utf-8',
        //                            success: function (data){
        //                                for(var i=0;i<7;i++){
        //                                    dates[i]=moment(data.data[i].payDate).format('YYYY-MM-DD');
        //                                };
        //                            }
        //                        });
        //                    }
        //                });
        //            }
        //        }
        //        else{
        //            $.springLemonDialog({
        //                content: '此款项的计划收款时间应小于下几个款项的计划回款时间',// 确认文本
        //                clickButton: function (sender, modal, index) {// 按钮事件处理
        //                    $(this).closeDialog(modal);
        //                }
        //            });
        //            return;
        //        }
        //    }
        //    else{
        //        $.springLemonDialog({
        //            content: '此款项的计划收款时间应大于上几个款项的计划回款时间',// 确认文本
        //            clickButton: function (sender, modal, index) {// 按钮事件处理
        //                $(this).closeDialog(modal);
        //            }
        //        });
        //        return;
        //    }
        //}
    });
})();